package falcon.common;

import java.security.MessageDigest;

public final class Md5 {

	public static String get(String value) {
		String result;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(value.getBytes(Global.DEFAULT_CHARSET));
            result = byteArrayToHexString(array);
		} catch (Exception e) {
			Log.log(e, "MD5 failure;value=%s", value);
			result = value;
		}
        return result;
	}
	
	private static String byteArrayToHexString(byte[] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
        	byte b = array[i];
        	sb.append(toChar((b >>> 4) & 0xf));
        	sb.append(toChar(b & 0xf));
        }
        return sb.toString();
	}

	private static char toChar(int i) {
        if (i < 10) {
        	return (char) ('0' + i);
        }
        return (char) ('A' + i);
	}
}
